import React, { Component, useEffect } from "react";
import {
    StyleSheet,
    Text,
    View,
    Pressable,
    TextInput,
    ScrollView,
    Dimensions,
} from "react-native";
import AntDesign from '@expo/vector-icons/AntDesign';

import * as FORM from "./Form"
import Constant from "../constant/Constant";
import util from "../common/utils/util";
import { CFlex, CColor, CStyle } from "../constant/css";
import { useSetState, useCurrent } from "../common/hooks";

//         {
//             key: 'status',
//             title: '状态',
//             type: SearchType.SINGLE,
//             data: status,
//             value: '',
//         },
/**
 * * APP 筛选框 组件
 * @param {object} props 参数项
 * @param {any[]} props.data 数据
 * @param {Function} props.onclick 事件
 * @param {string} props.bg 颜色
 * @returns {React.ReactElement}
 */
const SearchBar = (props) => {
    const {
        data = [], onclick = null,
        bg = CColor.White, childComponent = null,
    } = props

    const [state, setState] = useSetState({
        input: '',
        data: [],
        showTabView: -1,
    })

    const [ref, setRef] = useCurrent({
        viewObj: null,
        color: CColor.Black,
        count: 4,
    })

    useEffect(() => {
        doInitData()
    }, [data])

    const doInitData = () => {
        const obj = {
            [SearchType.SINGLE]: renderSingleView
        }

        setRef({
            viewObj: obj,
            color: bg === CColor.White ? CColor.Black : CColor.White,
        })

        const _state = {
            data,
        }
        setState(_state)
    }

    const updateTabData = (index, target = undefined) => {
        const { data = [] } = state
        let temp = target || data
        if (index <= ref.count - 1) {
            let showTabView = index
            temp.forEach((item, _) => {
                if (_ === index) {
                    if (item.visible) showTabView = -1
                    item.visible = !item.visible
                } else {
                    item.visible = false
                }
            })
            setState({
                showTabView,
                data: temp,
            })
        }
    }

    const setChooseData = ({ index, choose }) => {
        if (!Object.keys(choose).length) return
        const { data = [] } = state
        data[index].value = choose
        updateTabData(index, data)
        onclick?.(data)
    }

    // * 渲染组件 单选
    const renderSingleView = ({ item, index, showContent = false }) => {
        if (!showContent) { // 筛选栏展示
            return (
                <View key={item.key} style={{ flex: 1 }}>
                    <Pressable style={[CFlex.row, CFlex.cc]} onPress={() => updateTabData(index)}>
                        <View style={{ marginRight: 5 }}>
                            <Text numberOfLines={1} style={{ textAlign: 'center', color: ref.color }}>{item?.value?.key || item.title}</Text>
                        </View>
                        <AntDesign name={item.visible ? "up" : "down"} size={12} color={ref.color} />
                    </Pressable>
                </View>
            )
        }
        // 候选项展示
        const choose = item.value.value || ''
        return (
            <ScrollView showsVerticalScrollIndicator={false} >
                <View style={[CFlex.row, CFlex.wrap, CFlex.sc, styles.showContent, { flex: 1 }]}>
                    {item.data.map(_ =>
                        <Pressable key={_.value} style={[styles.tag_item, choose === _.value ? { borderColor: CColor.Blue } : {}]} onPress={() => setChooseData({ choose: _, index })}>
                            <Text style={{ fontSize: 12, color: choose === _.value ? CColor.Blue : ref.color }}>{_.key}</Text>
                        </Pressable>
                    )}
                </View>
            </ScrollView>
        )

    }

    // * type 判断渲染组件
    const renderViewByType = ({ item = {}, index, showContent = false }) => {
        const { viewObj } = ref
        if (!item?.type || !viewObj[item.type]) return null
        return viewObj[item.type]({ item, index, showContent })
    }

    // * 展示候选项组件
    const renderTabView = () =>
        <View style={[CFlex.row, CFlex.sc, { height: 40 }]}>
            {
                state.data.slice(0, ref.count).map((item, index) => renderViewByType({ item, index }))
            }
        </View>

    const renderTabChooseView = () =>
        <>
            <View style={[styles.tabChooseView, { borderColor: ref.color }]}>
                {renderViewByType({ item: state.data[state.showTabView], index: state.showTabView, showContent: true })}
            </View>
            <Pressable style={styles.tabChooseMask} onPress={() => { updateTabData(-1) }} />
        </>

    return (
        <View style={{ backgroundColor: bg, zIndex: 999 }}>
            {renderTabView()}
            {state.showTabView > -1 ? renderTabChooseView() : null}
        </View>
    )
}

/**
 * * APP 搜索 组件
 * @param {object} props 参数项
 * @param {string} props.bg 颜色
 * @param {boolean} props.showClear 展示清除
 * @param {string} props.title 搜索提示
 * @param {StyleProp<ViewStyle>} props.style 样式
 * @param {Function} props.onSearch 输入事件
 * @returns {React.ReactElement}
 */
export const Input = (props) => {
    const {
        title = '', onSearch = null, showClear = false,
        bg = CColor.White, style = {},
    } = props

    const [state, setState] = useSetState({
        input: '',
    })
    const [ref, setRef] = useCurrent({
        color: CColor.Black,
    })
    return (
        <View style={[CFlex.row, CFlex.cc, styles.input, { borderColor: ref.color, ...style }]}>
            <AntDesign name="search1" size={20} color={ref.color} />
            <View style={{ flex: 1, paddingLeft: 10 }}>
                <TextInput
                    style={{ height: 35 }}
                    onChangeText={newText => {
                        setState({ input: newText })
                    }}
                    onSubmitEditing={e => {
                        onSearch?.(state.input)
                    }}
                    value={state.input}
                    placeholderTextColor={ref.color}
                    selectionColor={ref.color}
                    placeholder={title || '请输入内容'}
                    textAlign="left"
                    returnKeyType="search"
                />
            </View>
            {showClear ?
                <Pressable
                    onPress={() => {
                        setState({ input: '' })
                        onSearch?.('')
                    }}>
                    <AntDesign name="closecircleo" size={20} color="black" />
                </Pressable> : null}
        </View>
    )
}

const tab_view_height = 180
const styles = StyleSheet.create({
    input: {
        borderWidth: 1,
        borderRadius: 35,
        marginVertical: 5,
        marginHorizontal: 20,
        paddingVertical: 5,
        paddingHorizontal: 15
    },
    showContent: {
        paddingTop: 5,
        paddingBottom: 5,
        width: '100%',
        height: tab_view_height,
    },
    tabChooseView: {
        borderTopWidth: 1,
        borderBottomWidth: 1,
        width: '100%',
        height: tab_view_height,
        backgroundColor: CColor.White,
    },
    tabChooseMask: {
        backgroundColor: 'rgba(0,0,0,0.6)',
        width: '100%',
        height: Dimensions.get('screen').height,
        position: 'absolute',
        top: 220,
    },
    tag_item: {
        paddingHorizontal: 10, paddingVertical: 4, marginVertical: 3, marginLeft: 5,
        borderRadius: 15,
        borderColor: CColor.Black,
        borderWidth: 1,
        backgroundColor: CColor.White
    },
    tag_item_choose: {
        borderColor: CColor.Origin,
        borderWidth: 1,
        backgroundColor: CColor.Origin
    },
})

export const SearchType = {
    SINGLE: 'SINGLE'
}
export default SearchBar